package com.zjy.user.service.impl;

import com.zjy.basic.exception.BusinessException;
import com.zjy.basic.util.Md5Utils;
import com.zjy.basic.util.StrUtils;
import com.zjy.org.domain.Employee;
import com.zjy.user.domain.Logininfo;
import com.zjy.user.domain.User;
import com.zjy.user.mapper.LogininfoMapper;
import com.zjy.user.mapper.UserMapper;
import com.zjy.user.service.UserService;
import com.zjy.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    @Transactional
    public void add(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //先添加logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//1是管理员
        logininfo.setDisable(true);

        //将logininfo对象添加到数据库，并生成自增长id
        logininfoMapper.add(logininfo);//获取到自增ID
        //将logininfoId设置到对象中
        user.setLogininfoId(logininfo.getId());

        //添加数据
        super.add(user);
    }

    @Override
    @Transactional
    public void del(Long id) {
        //查询对象
        User user = userMapper.findById(id);
        //删除logininfo信息
        logininfoMapper.del(user.getLogininfoId());
        //删除信息
        super.del(id);
    }

    @Override
    @Transactional
    public void update(User user) {
        //前端传过来的对象是没有登陆信息id
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //获取原来的对象
        User oldUser = userMapper.findById(user.getId());//loginfo_id
        //修改信息
        user.setLogininfoId(oldUser.getLogininfoId());

        //更新数据
        super.update(user);

        //修改登陆信息
        Logininfo oldLogininfo = logininfoMapper.findById(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,oldLogininfo);
        //设置会以前的id - 进行修改
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);
    }



    /**
     * 手机短信注册
     * @param map
     */
    @Override
    public void phoneRegister(Map<String, String> map) {
        String phone = map.get("phone");
        String phoneCode = map.get("phoneCode");
        String password = map.get("password");
        String passwordRepeat = map.get("passwordRepeat");

        //一：校验 - 空值校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode)
        || StringUtils.isEmpty(password)  || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("信息不能为空！");
        }
        //二：校验 - 密码是否一致
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致！");
        }
        //三：校验 - 手机验证码是否过期，是否正确
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if (obj==null){
            throw new BusinessException("手机验证码过期！");
        }
        if (!obj.toString().split(":")[0].equals(phoneCode)){
            throw new BusinessException("手机验证码错误！");
        }
        //四：添加到数据库，密码加密加盐(先加密再加盐！)
        User user = map2User(phone,password);
        Logininfo logininfo = user2Logininfo(user);
        //1.先添加t_logininfo
        logininfoMapper.add(logininfo);//添加完了会生成自增长id
        //2.再添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    /**
     * 邮箱注册
     * @param map
     */
    @Override
    public void registerEmail(Map<String, String> map) throws MessagingException {
        String email = map.get("email");
        String password = map.get("password");
        String passwordRepeat = map.get("passwordRepeat");

        //一.空值校验
        if(StringUtils.isEmpty(passwordRepeat) || StringUtils.isEmpty(email) || StringUtils.isEmpty(password) ){
            throw new BusinessException("信息不能为空");
        }
//        判断密码是否一致
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("密码不一致");
        }
        //判断
        List<User> users = userMapper.findAll();
        for (User user : users) {
            if(user.getEmail()!=null){
                if(user.getEmail().equals(email)){
                    throw new BusinessException("您的邮箱已经注册过了，请直接登录");
                }
            }
        }
        User user = map3User(email,password);
        Logininfo logininfo = user3Logininfo(user);
        logininfoMapper.add(logininfo);//添加后生成自增长的id
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);

        //3.发送邮件：告诉店铺管理员激活邮件使用
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("1432346052@qq.com");
        helper.setSubject("用户激活邮件");
        //true - 能够再内容中编写html标签 - 会解析
        User user1 = userMapper.findByEmail(email);
        helper.setText("<h1>你的账号已经注册!!!</h1><img src='http://123.207.27.208"
                        +"' ><a href='http://127.0.0.1:8080/user/active/"+user1.getId()+"'>点击该链接激活</a>",
                true);
        //收件人
        helper.setTo(user1.getEmail());
        javaMailSender.send(mimeMessage);
    }

    @Override
    public void active(User user) {
        System.out.println(user.getId());
        userMapper.updateState(user.getId(),1);
    }

    private User map3User(String email, String password) {
        User user = new User();
        user.setUsername(email);
        user.setEmail(email);
//       对密码和研制处理
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
//        对密码加盐
        String md5Paw = Md5Utils.encrypByMd5(password + salt);
        user.setPassword(md5Paw);
        user.setState(0);
        return user;
    }

    private Logininfo user3Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
//        从哪里拷贝到哪里
        BeanUtils.copyProperties(user,logininfo);
//        1是用户
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User map2User(String phone,String password){
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        //对密码和盐值进行处理
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(password + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    private Logininfo user2Logininfo(User user){
        Logininfo logininfo = new Logininfo();
        //底层会按照属性同名原则进行属性的拷贝：id,username,phone,email,salt,password
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//1表示用户
        logininfo.setDisable(true);
        return logininfo;
    }
}